/*
 * UrlPresenter.java
 * business
 *
 * Created by ChenTao on 2017/2/23.
 *
 * Copyright (c) 2017年 yidiandao. All rights reserved.
 */

package com.yidiandao.business.ui.url;

import android.os.Bundle;
import android.text.TextUtils;

import com.github.lzyzsd.jsbridge.BridgeHandler;
import com.github.lzyzsd.jsbridge.CallBackFunction;
import com.google.gson.Gson;
import com.yidiandao.business.constant.Intents;
import com.yidiandao.business.constant.ServerCode;
import com.yidiandao.business.data.bean.ShareEntity;
import com.yidiandao.business.data.event.RefreshEnrollResultStateEvent;
import com.yidiandao.business.data.event.SignEvent;
import com.yidiandao.business.data.model.ArticleModel;
import com.yidiandao.business.data.model.IArticleModel;
import com.yidiandao.business.data.net.JSInterface;
import com.yidiandao.business.data.net.exception.NetErrorHelper;
import com.yidiandao.business.data.net.exception.NetErrorInfo;
import com.yidiandao.business.data.recyclertype.Article;
import com.yidiandao.business.data.response.QueryEnrollPayStateResponse;
import com.yidiandao.business.utils.GsonProvider;
import com.yidiandao.business.utils.LogUtils;
import com.yidiandao.business.utils.PreferenceUtils;
import com.yidiandao.business.utils.UIUtils;
import com.yidiandao.business.utils.UrlUtils;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONObject;

import java.util.List;

/**
 * UrlPresenter
 * <p>
 * <p>Created by ChenTao(chentao7v@gmail.com) on 2017/2/23 9:18
 */
public class UrlPresenter implements UrlContract.Presenter {

    private UrlContract.View mUrlView;

    private Gson mGson = GsonProvider.getGson();

    private boolean mIsFreeScreenOrientation;

    private String mUrl;

    private boolean mIsOnlinePay;

    private String mOrderPayId;

    private ShareEntity mShareEntity;

    private boolean mIsFirstIn;

    private boolean mShareFeatureEnable;

    private String mSourceUrl;

    private Article mArticle;

    private boolean mIsArticle;

    private ArticleModel mArticleModel;

    private String mRecId;

    private String mArticleId;

    public UrlPresenter(UrlContract.View view, Bundle bundle) {
        mUrlView = view;
        mArticleModel = new ArticleModel();

        extraBundle(bundle);

        mUrlView.setPresenter(this);
    }

    public void extraBundle(Bundle bundle) {
        mIsFreeScreenOrientation = bundle.getBoolean(Intents.FREE_SCREEN_ORIENTATION);
        mSourceUrl = mUrl = bundle.getString(Intents.HTTP_URL);
        mIsOnlinePay = bundle.getBoolean(Intents.EXTRA_FOR_ONLINE_PAY);
        mOrderPayId = bundle.getString(Intents.EXTRA_ORDER_PAY_ID);
        mIsFirstIn = bundle.getBoolean(Intents.EXTRA_FIRST_IN);
        mShareFeatureEnable = bundle.getBoolean(Intents.EXTRA_ENABLE_SHARE_FEATURE);
        mRecId = bundle.getString(Intents.EXTRA_REC_ID);

        // 文章相关
        mIsArticle = bundle.getBoolean(Intents.EXTRA_ARTICLE);
        mArticleId = bundle.getString(Intents.EXTRA_ARTICLE_ID);

        if (!mIsArticle) {
            jointUrl();
        }
    }

    private void jointUrl() {
        // 在线支付
        if (!mIsOnlinePay) {
            mUrl = UrlUtils.jointUrl(mUrl);
        }
    }

    @Override
    public boolean checkIsArticle() {
        return mIsArticle;
    }

    @Override
    public void start() {
        mUrlView.setRequestedOrientation(mIsFreeScreenOrientation);
    }

    @Override
    public void getArticleInfoFromServer() {
        mArticleModel.getArticleInfo(mUrlView.getPagerTag(), mArticleId, new IArticleModel.OnLoadResultListener<Article>() {
            @Override
            public void onSuccess(Article article, boolean emptyData, boolean hasMore) {
                mArticle = article;
                mSourceUrl = mUrl = article.getUrl();

                // 显示底部栏
                mUrlView.setArticleOperatorLayoutVisible(true);
                mUrlView.setBottomLayoutData(mArticle);

                jointUrl();

                mUrlView.loadUrl();
            }

            @Override
            public void onFailed(String message) {

            }
        });
    }


    @Override
    public String getUrl() {
        return mUrl;
    }


    @Override
    public String getOrderPayId() {
        return mOrderPayId;
    }


    @Override
    public boolean isOnlinePay() {
        return mIsOnlinePay;
    }


    public boolean isFreeScreenOrientation() {
        return mIsFreeScreenOrientation;
    }


    @Override
    public boolean isFirstIn() {
        return mIsFirstIn;
    }


    public String getRecId() {
        return mRecId;
    }


    @Override
    public void registerJavaInterfaceForJs() {
        // 商品详情
        registerJavaInterfaceForJs(JSInterface.TO_GOODS_DETAIL_UI, new Callback() {
            @Override
            public void onJsCallback(String data) throws Exception {
                JSONObject jsonObject = new JSONObject(data);
                String goodsId = jsonObject.getString("goods_id");
                mUrlView.toGoodsDetailActivity(goodsId);
            }
        });

        // 店铺详情
        registerJavaInterfaceForJs(JSInterface.TO_SHOP_DETAIL_UI, new Callback() {
            @Override
            public void onJsCallback(String data) throws Exception {
                JSONObject jsonObject = new JSONObject(data);
                String supplierId = jsonObject.getString("supplier_id");
                mUrlView.toShopDetailActivity(supplierId);
            }
        });

        // 加入购物车
        registerJavaInterfaceForJs(JSInterface.ADD_TO_SHOPPING_CART, new Callback() {
            @Override
            public void onJsCallback(String data) throws Exception {
            }
        });

        // 去购物车
        registerJavaInterfaceForJs(JSInterface.TO_SHOPPING_CART_UI, new Callback() {
            @Override
            public void onJsCallback(String data) throws Exception {
                mUrlView.toShoppingCartFragment();
            }
        });

        // 去登录页面
        registerJavaInterfaceForJs(JSInterface.TO_LOGIN_UI, new Callback() {
            @Override
            public void onJsCallback(String data) throws Exception {
                mUrlView.toLoginActivity();
            }
        });

        // 去品牌商品页面
        registerJavaInterfaceForJs(JSInterface.TO_BRAND_GOODS_UI, new Callback() {
            @Override
            public void onJsCallback(String data) throws Exception {
                JSONObject jsonObject = new JSONObject(data);
                String brandName = jsonObject.getString("brand_name");
                String brandId = jsonObject.getString("brand_id");
                String supplierId = jsonObject.getString("supplier_id");
                mUrlView.toBrandGoodsActivity(brandName, brandId, supplierId);
            }
        });

        // 调起分享窗口  供用户选择分享方式
        registerJavaInterfaceForJs(JSInterface.INVOKE_CLIENT_SHARE, new Callback() {
            @Override
            public void onJsCallback(String data) throws Exception {
                mUrlView.doClientShare(mGson.fromJson(data, ShareEntity.class));
            }
        });

        // 返回是否显示分享按钮数据
        registerJavaInterfaceForJs(JSInterface.SHOW_CLIENT_SHARE, new Callback() {
            @Override
            public void onJsCallback(String data) throws Exception {
                mShareEntity = mGson.fromJson(data, ShareEntity.class);
                mUrlView.setShareIconVisible(!TextUtils.isEmpty(data));
            }
        });

        // 立即购买去确认订单页面
        registerJavaInterfaceForJs(JSInterface.SERVER_BUY_NOW, new Callback() {
            @Override
            public void onJsCallback(String data) throws Exception {
//                JSONObject jsonObject = new JSONObject(data);
//                String recJson = jsonObject.getJSONArray("rec_json").toString();

                mUrlView.toConfirmOrderActivity();
            }
        });

        // 支付成功的交互
        registerJavaInterfaceForJs(JSInterface.PAY_SUCCESS, new Callback() {
            @Override
            public void onJsCallback(String data) throws Exception {
                JSONObject jsonObject = new JSONObject(data);
                String orderPayId = jsonObject.getString("order_pay_id");
                String orderId = jsonObject.getString("order_id");
                mUrlView.toPayResultActivity(orderPayId, orderId);
                mUrlView.finishActivity();
            }
        });

        // 报名活动支付成功
        registerJavaInterfaceForJs(JSInterface.ENROLL_PAY_SUCCESS, new Callback() {
            @Override
            public void onJsCallback(String data) throws Exception {
                // 点击交互,被告知支付成功
                postRefreshEnrollResultStateEvent(true);
                mUrlView.finishActivity();
            }
        });
        //查看红包
        registerJavaInterfaceForJs(JSInterface.TO_BONUS_UI, new Callback() {
            @Override
            public void onJsCallback(String data) throws Exception {
                mUrlView.toRedPacketActivity();
            }
        });
        //抽奖记录
        registerJavaInterfaceForJs(JSInterface.WATCH_PRIZE, new Callback() {
            @Override
            public void onJsCallback(String data) throws Exception {
                mUrlView.toSignHistoryActivity();
            }
        });

        //签到成功
        registerJavaInterfaceForJs(JSInterface.SIGN_SUCCESS, new Callback() {
            @Override
            public void onJsCallback(String data) throws Exception {
                EventBus.getDefault().post(new SignEvent(false));
            }
        });

        // 去活动页面
        registerJavaInterfaceForJs(JSInterface.TO_ACTIVITY_UI, new Callback() {
            @Override
            public void onJsCallback(String data) throws Exception {
                JSONObject jsonObject = new JSONObject(data);
                String url = jsonObject.getString("url");
                mUrlView.toUrlActivity(UrlUtils.jointUrl(url));
            }
        });

        // 去优惠券页面
        registerJavaInterfaceForJs(JSInterface.TO_COUPON_UI, new Callback() {
            @Override
            public void onJsCallback(String data) throws Exception {
                mUrlView.toCouponActivity();
            }
        });
    }


    @Override
    public ShareEntity getShareData() {
        return mShareEntity;
    }


    @Override
    public void tellJsLoginStateChanged() {
        // WebView登录刷新
        String token = PreferenceUtils.getToken(UIUtils.getContext());
        String tokenJson = "{\"token\":" + "\"" + token + "\"}";
        callJsClientHasDone(JSInterface.CLIENT_LOGIN_SUCCESS, tokenJson, null);
    }


    @Override
    public void tellJsClientShareSuccess() {
        callJsClientHasDone(JSInterface.CLIENT_SHARE_SUCCESS, null, null);
    }


    @Override
    public ShareEntity createUrlShareData() {
        ShareEntity shareEntity = new ShareEntity();
        shareEntity.setTitle(mUrlView.getTitle());
        shareEntity.setUrl(mSourceUrl);
        shareEntity.setText(mUrlView.getTitle());
        List<String> urlsFromHtml = mUrlView.getImagesUrlsFromHtml();
        if (null == urlsFromHtml || urlsFromHtml.size() == 0) {
            shareEntity.setImg("https://b.yidiandao.com/yidiandao_sj_wx/Public/img/ydd.png");
        } else {
            shareEntity.setImg(urlsFromHtml.get(0));
        }
        return shareEntity;
    }


    @Override
    public boolean shareFeatureEnable() {
        return mShareFeatureEnable;
    }


    @Override
    public void likeArticle(final Article article) {
        mArticleModel.likeArticle(mUrlView.getPagerTag(), article.getArticleId(), new IArticleModel.OnLoadResultListener() {
            @Override
            public void onSuccess(Object o, boolean emptyData, boolean hasMore) {
                // 点赞或者取消点赞
                boolean like = article.getHasVote() == 1;
                article.setHasVote(like ? 0 : 1);
                String voteCount = article.getVoteCount();
                int count = 0;
                try {
                    count = Integer.parseInt(voteCount);
                } catch (NumberFormatException e) {
                    count = 0;
                } finally {
                    if (like) {
                        count--;
                    } else {
                        count++;
                    }

                    if (count < 0) {
                        count = 0;
                    }
                    article.setVoteCount(count + "");
                    mUrlView.notifyLikeCountChanged();
                }
            }


            @Override
            public void onFailed(String message) {

            }
        });
    }


    @Override
    public void checkEnrollOnlinePayState() {
        if (mRecId == null) {
            return;
        }

        LogUtils.e("rec_id --> " + mRecId);
        mArticleModel.getEnrollPayState(mUrlView.getPagerTag(), mRecId, new IArticleModel.OnLoadResultListener<QueryEnrollPayStateResponse.Data>() {
            @Override
            public void onSuccess(QueryEnrollPayStateResponse.Data data, boolean emptyData, boolean hasMore) {
                mUrlView.finishActivity();
                // 报名支付成功/失败,都需要告知不能再在文章详情页面点击报名按钮
                postRefreshEnrollResultStateEvent(data.getPayState() == 1);

                if (data.getPayState() == 0) {
                    // 报名支付失败
                    mUrlView.toEnrollPayFailedActivity(getRecId());
                }

                LogUtils.e("支付结果 --> " + data.toString());
            }


            @Override
            public void onFailed(String message) {

            }
        });
    }

    @Override
    public void postRefreshEnrollResultStateEvent(boolean paySuccess) {
        EventBus.getDefault().post(new RefreshEnrollResultStateEvent(true, paySuccess));
    }


    private void callJsClientHasDone(String handlerName, String data, CallBackFunction callBack) {
        mUrlView.getWebView().callHandler(handlerName, data, callBack);
    }


    private void reportError(Exception e, String url) {
        // 打印错误到控制台,并上传部分错误到友盟
        NetErrorInfo netErrorInfo = new NetErrorInfo("Cause By JSInterface",
                ServerCode.JSON_PARSE_ERROR, e);
        NetErrorHelper.reportError(UrlFragment.class, url, null, netErrorInfo, null);
    }


    private void registerJavaInterfaceForJs(final String javaInterfaceForJs, final Callback callback) {
        mUrlView.getWebView().registerHandler(javaInterfaceForJs, new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                try {
                    if (callback != null) {
                        callback.onJsCallback(data);
                    }
                } catch (Exception e) {
                    reportError(e, javaInterfaceForJs);
                }
            }
        });
    }


    /**
     * JS回掉接口
     */
    private interface Callback {
        void onJsCallback(String data) throws Exception;
    }
}
